feat: CommunityToolkit.Aspire.Hosting.K3s — k3s Kubernetes cluster hosting integration#1322
feat: CommunityToolkit.Aspire.Hosting.K3s — k3s Kubernetes cluster hosting integration#1322edmondshtogu wants to merge 16 commits into
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/CommunityToolkit/Aspire/main/eng/scripts/dogfood-pr.sh | bash -s -- 1322Or
iex "& { $(irm https://raw.githubusercontent.com/CommunityToolkit/Aspire/main/eng/scripts/dogfood-pr.ps1) } 1322" |
|
@dotnet-policy-service agree |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 37 out of 38 changed files in this pull request and generated 15 comments.
Comments suppressed due to low confidence (4)
src/CommunityToolkit.Aspire.Hosting.K3s/K3sBuilderExtensions.Manifest.cs:95
- This
asynccallback has no await, which will produce CS1998 and be treated as an error in this repo. Use a completedTaskreturn (or a synchronous overload) so the project builds cleanly.
resourceBuilder.WithContainerFiles("/k8s-manifests", async (ctx, ct) =>
{
if (Directory.Exists(absolutePath))
src/CommunityToolkit.Aspire.Hosting.K3s/K3sBuilderExtensions.Helm.cs:91
- This
asyncexpression-bodied callback has no await, so CS1998 will be emitted and treated as an error. Return a completed task (or use a synchronous overload) instead of marking the lambda async.
.WithContainerFiles("/helm-values", async (ctx, ct) =>
release.ValuesFiles
.Select((hostPath, i) => (ContainerFileSystemItem)new ContainerFile
src/CommunityToolkit.Aspire.Hosting.K3s/K3sInProcessPortForwarder.cs:152
- The same empty-selector case here can select the first ready pod in the namespace and forward traffic to an unrelated workload. Services without selectors are valid in Kubernetes, so the forwarder should not treat an empty selector as "all pods".
var selector = string.Join(",",
(svc.Spec.Selector ?? new Dictionary<string, string>()).Select(kv => $"{kv.Key}={kv.Value}"));
var pods = await k8sClient.CoreV1
.ListNamespacedPodAsync(@namespace, labelSelector: selector, cancellationToken: ct)
tests/CommunityToolkit.Aspire.Hosting.K3s.Tests/K3sClusterResourceTests.cs:253
- This test name says it verifies the pod subnet argument, but the assertion only checks that a cluster resource exists. It would still pass if
WithPodSubnetstopped adding--cluster-cidr, so it should assert the command-line args.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
|
@aaronpowell, @IEvangelist, @marshalhayes or @tommasodotNET can one of you please review the PR (sorry for pulling you in the comment, but you are the most active contributors here) |
|
@davidfowl do you know who can help with the review here? |
Closes #1321
Overview of changes
Adds CommunityToolkit.Aspire.Hosting.K3s, a hosting integration that runs a lightweight Kubernetes cluster as an Aspire resource tree. Developers can declare a local Kubernetes cluster in Program.cs — with Helm charts, manifests, and exposed service endpoints — the same way they add Redis or PostgreSQL. No external tooling beyond a compatible container runtime (Docker or Podman) is required.
What's included
New package: src/CommunityToolkit.Aspire.Hosting.K3s/
New Tests & Examples:
ubuntu-latestonly (Windows excluded — GitHub-hosted runners do not support privileged Linux containers reliably);bitnami/nginxas the test chart.Key design decisions
Health check via bind-mount, not docker exec. k3s writes its kubeconfig to
K3S_KUBECONFIG_OUTPUT=/tmp/k3s-kubeconfig/kubeconfig.yaml, bind-mounted toAppHostDirectory/.k3s/{name}/cluster/on the host. The health check pollsFile.Exists, rewrites server URLs intolocal/andcontainer/variants, then confirms node readiness viaIKubernetes.CoreV1.ListNodeAsync. No shell access, nodocker exec, works with any container runtime.Helm and kubectl run as containers.
HelmReleaseResourceandK8sManifestResourceextendContainerResourceand are shown as children of the cluster in the Aspire dashboard. The install/apply script is injected viaWithContainerFiles. They cannot useWaitFor(cluster)(Aspire forbids a child waiting for its parent), so their scripts poll for/root/.kube/kubeconfig.yaml— which only appears after the cluster health check passes — before proceeding. Consumers useWaitForCompletion(helmRelease)since these are run-to-completion containers.Kubeconfig delivered via bind-mount to all containers.
WithReference(cluster)on containers, the helm installer, and the kubectl applier all bind-mountAppHostDirectory/.k3s/{name}/container/(server:https://{name}:6443) at a known in-container path and setKUBECONFIG. Bind-mount is used uniformly so the kubeconfig updates automatically if the cluster is recreated without restarting dependent containers. NoKUBECONFIG_DATAbase64 encoding — all standard Kubernetes tooling (kubectl,helm, KubernetesClient SDK) works without custom bootstrap code.Kustomize auto-detected.
AddK8sManifestchecks forkustomization.yamlat configuration time: if present, it bind-mounts the directory (preserving relative base references) and useskubectl apply -k; otherwise it uses an asyncWithContainerFilescallback to copy only the YAML files at container-start time and applies withkubectl apply -f --server-side. The callback approach avoids Aspire's build-time path validation on the string overload. The script auto-detects the mode at runtime.Service exposure without NodePort.
K3sServiceEndpointResourcestarts an in-process KubernetesClient WebSocket port-forward bound to0.0.0.0:{hostPort}. Host resources receiveservices__{name}__url=http(s)://localhost:{port}; container resources receiveservices__{name}__url=http(s)://host.docker.internal:{port}with--add-host=host.docker.internal:host-gatewayinjected automatically viaContainerRuntimeArgsCallbackAnnotation(DCP does not inject this on Linux). The forwarder resolvestargetPortfrom the service spec (not the service port) before opening the pod WebSocket, and only signals ready after a running pod is confirmed — not when the TCP listener starts.Image overrides via K3sClusterOptions. The helm and kubectl container images are configurable via
HelmImage/HelmTag/HelmRegistryandKubectlImage/KubectlTag/KubectlRegistryonK3sClusterOptions. Defaults:docker.io/alpine/helm:3.17.3anddocker.io/alpine/k8s:1.32.3.Robustness fixes from review.
WithK3sVersionpropagates the image tag to all agent nodes (prevents server/agent version skew).AddServiceEndpointvalidates the port is in the range 1–65535. Helm values files are indexed as{i}-{filename}so declaration order is preserved and basename collisions are safe. All helm--setvalues and--valuespaths are POSIX single-quote escaped viaShellEscape().Usage
PR Checklist
Other information
Security Assumptions
This change assumes local development only. k3s runs in privileged mode (required by k3s/containerd). The bind-mounted kubeconfig directory is readable only by the AppHost user.
KubernetesClientConfigurationuses the embedded CA cert from the kubeconfig; noDangerousAcceptAnyServerCertificateValidatoris used.Remaining Follow-up Work
HelmReleaseResource,K8sManifestResource,K3sServiceEndpointResourcein guest SDK code-gen (Slice 6 ATS completeness).K3sClusterResourcehas no production counterpart configured.